#!/bin/sh
# 编译安装Spine
App=cacti-spine
AppName=Spine
AppBase=/App
AppDir=$AppBase/spine
AppConf=$AppDir/etc/spine.conf

AppSrcBase=/App/src
AppSrcFile=$App-*.tar.*
AppSrcDir=$(find $AppSrcBase -maxdepth 1 -name "$AppSrcFile" -type f 2> /dev/null | sed -e 's/.tar.*$//' -e 's/^.\///')

MySQLDir=/App/mysql
ScriptDir=$(dirname $0)
ScriptFile=$(basename $0)
DB_Host=$(cat $ScriptDir/cacti | grep "database_hostname=" | awk -F= '{print $2}')
DB_Database=$(cat $ScriptDir/cacti | grep "database_default=" | awk -F= '{print $2}')
DB_User=$(cat $ScriptDir/cacti | grep "database_username=" | awk -F= '{print $2}')
DB_Pass=$(cat $ScriptDir/cacti | grep "database_password=" | awk -F= '{print $2}')
DB_Port=$(cat $ScriptDir/cacti | grep "database_port=" | awk -F= '{print $2}')
DB_PreG=0

finstall() {
    test -d "$AppDir" && echo "$AppName 已安装" || fupdate
}

fupdate() {
fbackup
cd $AppSrcBase
test -d "$AppSrcDir" && rm -rf $AppSrcDir

tar zxf $AppSrcFile || tar jxf $AppSrcFile
cd $AppSrcDir

./configure --prefix=$AppDir --with-results-buffer=2048 --with-mysql=$MySQLDir
make && make install

if [ $? -eq 0 ]; then
    echo "$AppName 安装成功"
else
    echo "$AppName 安装失败"
    exit 1
fi

cat > $AppConf << EOF
DB_Host         $DB_Host 
DB_Database     $DB_Database
DB_User         $DB_User
DB_Pass         $DB_Pass
DB_Port         $DB_Port
DB_PreG         $DB_PreG
EOF
}

fbackup() {
    Day=$(date +%Y-%m-%d)
    BackupFile=spine-$Day.tgz
    test -d "$AppDir" && cd $AppBase && tar zcvf $BackupFile $App
}

case "$1" in
    "install" ) finstall;;
    "update"  ) fupdate;;
    "backup"  ) fbackup;;
    * )
    echo "用法：$ScriptFile {install|update|backup}"
    ;;
esac
